/*
 License
 
 Copyright © 2012 Kevin Kimmich
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights to 
 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 the Software, and to permit persons to whom the Software is furnished to do so, 
 subject to the following conditions:
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
 FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include <signal.h>
#include <ctype.h>
#include "crcore.h"
#include "messaging.h"
#include "kuato_http.h"
#include "kuato_http_operations.h"
#include "kuato_server.h"

static void* chunked_handler_wrapper(int argc, void** argv)
{
	method* m = argv[0];
	m->rule->handle_request( m );
	return NULL;
}

static core_thread_t* create_chunked_handler(method* m)
{
	void* argv[1];
	argv[0]=m;
	return core_thread_create_attached(chunked_handler_wrapper,1,argv);
}

static void destroy_chunked_handler( core_thread_t* th )
{
	core_thread_destroy(th);
}

static int __write_context(method* m)
{
	io_result result;
	int bytes_sent;
	int write_err = 0;
	exception_env_t e = INIT_EXCEPTION;
	TRY
	{
		context_wait_write(m->ctx,FOREVER,&result,&bytes_sent);
	}
	CATCH(e)
	{
		write_err=1;
	}
	FINALIZE
	return write_err;
}

void chunked_handler_func(http_match_rule_t* rule, method* m)
{
	const char *mime_type=get_mime_type_from_method(m);	
	core_thread_t* th = create_chunked_handler(m);
	stream* outstream = &m->ctx->write_stream;
	m->req.status = HTTP_OK;
	m->rule = rule;
	stream_init(&m->server_input_stream,CONFIG_CHUNK_SIZE);

	int header_sent = 0;
	int write_err=0;
	char buf[CONFIG_CHUNK_SIZE];
	
	for(;write_err==0;)
	{
		if(header_sent==0)
		{
			//write the header
			stream_printf(outstream,"HTTP/1.1 %d %s\r\n",m->req.status.code,m->req.status.information_string);
			stream_printf(outstream,"%s\r\n",CONFIG_SERVER_RESPONSE_HEADER_STRING);

			stream_printf(outstream,"TRANSFER-ENCODING: CHUNKED\r\n");
			stream_printf(outstream,"CONTENT-TYPE: %s\r\n",mime_type);
			stream_printf(outstream,"EXPIRES: Mon, 26 Jul 1997 05:00:00 GMT\r\n");
			stream_printf(outstream,"Cache-Control: no-store, no-cache, must-revalidate\r\n");
			stream_printf(outstream,"Cache-Control: post-check=0, pre-check=0\r\n");
			stream_printf(outstream,"Pragma: no-cache\r\n");
			stream_printf(outstream,"\r\n");
			
			write_err = __write_context(m);
			
			header_sent=1;
		}
		else
		{
			//write the next chunk of data
			size_t block_length;
			int bytes_read;
			
			bytes_read = stream_blocking_read(&m->server_input_stream,&block_length,sizeof(size_t));
			
			if(bytes_read < 0) //the stream has been terminated
				break;
			
			if(bytes_read != sizeof(size_t))
			{
				//an error occurred
				printf("media stream error in http_protocol.c line %d\n",__LINE__);
				exit(-1);
			}
			
			if(block_length > 0)
			{
				//there is some block to write
				int total=0;
				
				for(;total < block_length;)
				{
					//only send up to a CONFIG_CHUNK_SIZE in the chunk
					int len = block_length - total;
					if(len > CONFIG_CHUNK_SIZE)
					{
						len=CONFIG_CHUNK_SIZE;
					}
					
					bytes_read = stream_blocking_read(&m->server_input_stream,buf,len);
					
					if(bytes_read > 0)
					{
						total += bytes_read;
						stream_printf(outstream,"%x\r\n",bytes_read);
						stream_from_memory(outstream,buf,bytes_read);
						stream_printf(outstream,"\r\n");
						
						write_err = __write_context(m);
					}
				}
			}
			else
			{
				stream_printf(outstream,"0\r\n\r\n");
				write_err = __write_context(m);
			}
		}
	}
	
	stream_blocking_cleanup(&m->server_input_stream);
	
	destroy_chunked_handler(th);

	printf("Destroyed handler\n");
	
	m->status = METHOD_COMPLETE;
}

int http_server_write_chunk( method* m, size_t length, void* data )
{
	int rv = stream_blocking_write(&m->server_input_stream,(void*)&length,sizeof(length));
	if(rv < 0)
		return -1;
	
	if(length==0)
		return 0;
	
	rv = stream_blocking_write(&m->server_input_stream,data,length);
	if(rv < 0)
		return -1;
	
	return 0;
}
